package common.util;

import java.util.function.Consumer;
import java.util.function.Function;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 规则表达式工具类
 *
 * @Author wangyue
 * @Version 3.0
 * @Date 2023-11-14
 */
public class RegexUtils {

    public static void findAll(String text, Pattern pattern, Consumer<Matcher> todo) {
        Matcher matcher = pattern.matcher(text);
        StringBuffer result = new StringBuffer();
        while (matcher.find()) {
            todo.accept(matcher);
        }
    }

    public static String replaceAll(String text, Pattern pattern, Function<Matcher, String> valueFactory) {
        Matcher matcher = pattern.matcher(text);
        StringBuffer result = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(result, valueFactory.apply(matcher));
        }
        matcher.appendTail(result);
        return result.toString();
    }

}
